package com.cf.oss.core;

import com.cf.id.SnowflakeId;
import com.cf.util.DateUtil;
import com.cf.util.RequestUtil;
import com.cf.util.UploadUtils;
import com.cf.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author ltq 批量上传图片和附件
 */

@Slf4j
public class FileUploadController {

    public FileUploadController() {
        log.info("上传controller实例化完成！");
    }

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private OSSService ossService;

    @Autowired
    private SnowflakeId id;

    private static long maxSize = 1000000;
    private static HashMap<String, String> extMap = new HashMap<String, String>();

    static {
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file",
                "doc,docx,xls,xlsx,ppt,pptx,pdf,htm,html,txt,zip,rar,gz,bz2");
    }

    @RequestMapping(value = "/uploadFiles")
    public ResponseVo<List<String>> uploadFiles(HttpServletRequest request, HttpServletResponse response) throws Exception {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("file");

        String reqPath = null;
        String realFileName = null;
        String suffix = null;
        List<String> fileUrls = new ArrayList();
        for (MultipartFile file : files) {
            realFileName = file.getOriginalFilename();
            /** 得到图片保存目录的真实路径 **/
            String fileRealPathDir = RequestUtil.getRealPath();
            /** 获取文件的后缀 **/
            suffix = realFileName.substring(realFileName.lastIndexOf("."));
            // /**使用UUID生成文件名称**/
            String fileImageName = getOssFilePath(suffix);// 构建文件名称
            /** 拼成完整的文件保存路径加文件 **/
            String fileName = fileRealPathDir + File.separator
                    + fileImageName;
            File newFile = new File(fileName);

            String result = getOssFileDir() + fileImageName;
            try {
                FileCopyUtils.copy(file.getBytes(), newFile);
                ossService.uploadFile(new UploadFileRequestBuilder(ossConfig.getDefaultBucketName(), result).uploadFile(fileName).build());
                log.debug("imgpath:{}", getOssFileDir() + fileImageName);
                UploadUtils.deleteFile(fileName);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
                log.debug("图片上传失败：" + e.getMessage());
                log.error(e.getMessage(), e);
            }
            reqPath = result;
            // 返回路径给页面上传

            fileUrls.add(ossConfig.getDomain() + reqPath);
        }
        return ResponseVo.success(fileUrls, "上传处理成功！");
    }

    private String getOssFilePath(String suffix) {
        return id.nextId() + suffix;
    }

    private String getOssFileDir() {
        return DateUtil.getDateFormat("yyyy/MM/");
    }


}
